<template>
  <div>
    <div class="app-container">
      <div class="page_header">{{ID?'编辑':'添加'}}经销商</div>
      <el-tabs v-model="tabTypeInfo" type="card">
        <el-tab-pane label="基本信息" name="basicInfo"></el-tab-pane>
        <el-tab-pane label="责任人信息" name="responsibleInfo"></el-tab-pane>
        <el-tab-pane label="营业信息" name="businessInfo"></el-tab-pane>
        <el-tab-pane label="账户信息" name="accountInfo"></el-tab-pane>
      </el-tabs>
      <el-col :span="12">
        <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="130px">
          <div v-show="tabTypeInfo === 'basicInfo'">
            <el-form-item label="经销商名称" prop="dealerName">
              <el-input v-model="formData.dealerName" placeholder="请输入经销商名称" :maxlength="20" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="经销商编号" prop="dealerNumber">
              <el-input v-model="formData.dealerNumber" placeholder="请输入经销商编号" :maxlength="50" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="座机/手机" prop="dealerPhone">
              <el-input v-model="formData.dealerPhone" placeholder="请输入座机/手机" clearable :style="{width: '100%'}" :max="15"></el-input>
            </el-form-item>
            <el-form-item label="运营情况" prop="dealerStatus">
              <el-select v-model="formData.dealerStatus" placeholder="请选择运营情况" clearable :style="{width: '100%'}">
                <el-option v-for="(item, index) in dealerStatusOptions" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="分配权重" prop="dealerProportion">
              <el-input-number v-model="formData.dealerProportion" placeholder="请输入" :step="1" :precision="0" :max="10000"></el-input-number>
            </el-form-item>
            <el-form-item label="省市区" prop="dealerAddress">
              <CityPicker ref="cityPicker" size="small" clearable placeholder="请选择" v-model="formData.dealerAddress" />
            </el-form-item>
            <el-form-item label="详细地址" prop="dealerAddressDetail">
              <el-input v-model="formData.dealerAddressDetail" placeholder="请输入详细地址" :maxlength="50" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="经销商类别" prop="dealerType">
              <el-select v-model="formData.dealerType" placeholder="请选择经销商类别" clearable :style="{width: '100%'}">
                <el-option v-for="(item, index) in dealerTypeOptions" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="经销商类型" prop="dealerFunList">
              <el-checkbox-group v-model="formData.dealerFunList" size="medium">
                <el-checkbox v-for="(item, index) in dealerRoleListOptions" :key="index" :label="item.value" :disabled="item.disabled">{{item.label}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="经销商权限" prop="dealerRoleList">
              <el-checkbox-group v-model="formData.dealerRoleList" size="medium">
                <el-checkbox v-for="(item, index) in dealerRoleListOptions" :key="index" :label="item.value" :disabled="item.disabled">{{item.label}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="代理区域" prop="areaData">
              <div style="display:flex;align-items:flex-start;">
                <el-button style="height:32px;margin-top: 2px;" size="small" type="primary" icon="el-icon-plus" @click="handleAreaDataAdd">增加</el-button>
                <div style="margin-left:10px;">
                  <div v-for="(perCity,index) of formData.areaData" :key="index">
                    <CityPicker :withAll="true" size="small" clearable placeholder="请选择" v-model="formData.areaData[index]" />
                    <el-button style="margin-left: 10px;" size="small" type="danger" icon="el-icon-minus" circle @click="handleAreaDataMinus(index)"></el-button>
                  </div>
                </div>
              </div>
            </el-form-item>
          </div>

          <div v-show="tabTypeInfo === 'responsibleInfo'">
            <el-form-item label="负责人姓名" prop="dealerUserName">
              <el-input v-model="formData.dealerUserName" placeholder="请输入负责人姓名" :maxlength="20" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="负责人电话" prop="dealerUserPhone">
              <el-input v-model="formData.dealerUserPhone" placeholder="请输入负责人电话" :maxlength="20" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="法人姓名" prop="dealerUserFname">
              <el-input v-model="formData.dealerUserFname" placeholder="请输入法人姓名" :maxlength="20" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="法人电话" prop="dealerUserFphone">
              <el-input v-model="formData.dealerUserFphone" placeholder="请输入法人电话" :maxlength="20" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="法人身份证号" prop="dealerUserNumber">
              <el-input v-model="formData.dealerUserNumber" placeholder="请输入法人身份证号" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>

            <el-form-item label="身份证正面">
              <el-upload
                ref="dealerUserZimgUrl"
                :file-list="dealerUserZimgUrlFileList"
                :headers="urlHeaders"
                :action="urlAction"
                :limit="1"
                :before-upload="urlBeforeUpload"
                :on-success="handleFileSuccess"
                list-type="picture"
                accept="image/*"
                :on-remove="handleRemoveZ"
              >
                <el-button :disabled="sfzzm" size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传不超过 2MB 的 jpg,png 文件</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="身份证反面">
              <el-upload
                ref="dealerUserFimgUrl"
                :file-list="dealerUserFimgUrlFileList"
                :headers="urlHeaders"
                :action="urlAction"
                :limit="1"
                :before-upload="urlBeforeUpload"
                :on-success="handleFileSuccess"
                list-type="picture"
                accept="image/*"
                :on-remove="handleRemoveF"
              >
                <el-button :disabled="sfzfm" size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传不超过 2MB 的 jpg,png 文件</div>
              </el-upload>
            </el-form-item>
          </div>

          <div v-show="tabTypeInfo === 'businessInfo'">
            <el-form-item label="营业执照复印件(盖公章)">
              <el-upload
                ref="dealerLicenseUrl"
                :file-list="dealerLicenseUrlFileList"
                :headers="urlHeaders"
                :action="urlAction"
                :limit="1"
                :before-upload="urlBeforeUpload"
                :on-success="handleFileSuccess"
                list-type="picture"
                accept="image/*"
                :on-remove="handleRemoveYY"
              >
                <el-button :disabled="yyzz" size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传不超过 2MB 的 jpg,png 文件</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="营业执照营业范围" prop="dealerLicenseContent">
              <el-input
                v-model="formData.dealerLicenseContent"
                type="textarea"
                placeholder="请输入营业执照营业范围"
                :maxlength="500"
                :autosize="{minRows: 4, maxRows: 4}"
                :style="{width: '100%'}"
              ></el-input>
            </el-form-item>
            <el-form-item label="营业执照有效期起" prop="dealerLicenseStart">
              <el-date-picker
                v-model="formData.dealerLicenseStart"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                :style="{width: '100%'}"
                placeholder="请选择营业执照有效期起"
                clearable
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="营业执照有效期止" prop="dealerLicenseEnd">
              <el-date-picker
                v-model="formData.dealerLicenseEnd"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                :style="{width: '100%'}"
                placeholder="请选择营业执照有效期止"
                clearable
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="公司规模" prop="dealerScale">
              <el-input v-model="formData.dealerScale" placeholder="请输入公司规模" :maxlength="50" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="营业额" prop="dealerTurnover">
              <el-input v-model="formData.dealerTurnover" placeholder="请输入营业额" :maxlength="50" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="代理产品" prop="dealerProduct">
              <el-input v-model="formData.dealerProduct" placeholder="请输入代理产品" :maxlength="50" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="代理等级" prop="dealerLevel">
              <el-select v-model="formData.dealerLevel" placeholder="请选择代理等级" clearable :style="{width: '100%'}">
                <el-option v-for="(item, index) in dealerLevelOptions" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="代理时间" prop="dealerStart">
              <el-date-picker
                v-model="formData.dealerStart"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                :style="{width: '100%'}"
                placeholder="请选择代理时间"
                clearable
              ></el-date-picker>
            </el-form-item>
          </div>

          <div v-show="tabTypeInfo === 'accountInfo'">
            <el-form-item label="开户行" prop="dealerAccountAddress">
              <el-input v-model="formData.dealerAccountAddress" placeholder="请输入开户行" :maxlength="50" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="银行卡号" prop="dealerAccountNumber">
              <el-input v-model="formData.dealerAccountNumber" placeholder="请输入银行卡号" :maxlength="50" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="开户姓名" prop="dealerAccountName">
              <el-input v-model="formData.dealerAccountName" placeholder="请输入开户姓名" :maxlength="10" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="预留手机号" prop="dealerAccountPhone">
              <el-input v-model="formData.dealerAccountPhone" placeholder="请输入预留手机号" :maxlength="50" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
          </div>
          <el-form-item size="large">
            <el-button type="primary" :disabled="pending" @click="submitForm">全部提交</el-button>
            <el-button @click="resetForm">全部重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </div>
  </div>
</template>

<script>
import { getDealerDetail, addDealer, updateDealer } from '@/api/dealer/index'
import { getProtypeList } from '@/api/product/protype'
import { uploadUrl } from '@/settings.js'
import { getToken } from '@/utils/auth'
import CityPicker from '@/components/cityPicker'

const imgPropArr = ['dealerUserZimgUrl', 'dealerUserFimgUrl', 'dealerLicenseUrl']
export default {
  name: 'Dealeredit',
  components: {
    CityPicker
  },
  data() {
    return {
      tabTypeInfo: 'basicInfo',

      formData: {
        dealerName: undefined,
        dealerPhone: undefined,
        dealerStatus: undefined,
        dealerProportion: undefined,
        //
        dealerAddress: [],
        dealerAddressDetail: undefined,
        dealerType: undefined,
        dealerFunList: [],
        dealerRoleList: [],
        //
        areaData: [[]],
        //
        dealerUserName: undefined,
        dealerUserPhone: undefined,
        dealerUserFname: undefined,
        dealerUserFphone: undefined,
        dealerUserNumber: undefined,

        dealerUserZimgUrl: [],
        dealerUserFimgUrl: [],
        dealerLicenseUrl: [],

        dealerLicenseContent: undefined,
        dealerLicenseStart: null,
        dealerLicenseEnd: null,
        dealerScale: undefined,
        dealerTurnover: undefined,
        dealerProduct: undefined,
        dealerLevel: undefined,
        dealerStart: null,
        dealerNumber: undefined,
        dealerAccountAddress: undefined,
        dealerAccountNumber: undefined,
        dealerAccountName: undefined,
        dealerAccountPhone: undefined
      },
      rules: {
        dealerName: [
          {
            required: true,
            message: '请输入经销商名称',
            trigger: 'blur'
          }
        ],
        dealerNumber: [
          {
            required: true,
            message: '请输入经销商编号',
            trigger: 'blur'
          }
        ],
        dealerPhone: [
          {
            required: true,
            message: '请输入座机/手机',
            trigger: 'blur'
          },
          {
            pattern: /(\d{3,4}-?)?\d{7,8}|1\d{10}/,
            message: '格式有误',
            trigger: 'blur'
          }
        ],
        dealerStatus: [
          {
            required: true,
            message: '请选择运营情况',
            trigger: 'change'
          }
        ],
        dealerProportion: [
          {
            required: true,
            message: '请输入座机/手机',
            trigger: 'change'
          }
        ],
        dealerAddress: [
          {
            required: true,
            type: 'array',
            message: '请选择省市区',
            trigger: 'change'
          }
        ],
        dealerAddressDetail: [
          {
            required: true,
            message: '请输入详细地址',
            trigger: 'blur'
          }
        ],
        dealerType: [
          {
            required: true,
            message: '请选择经销商类别',
            trigger: 'change'
          }
        ],
        dealerFunList: [
          {
            required: true,
            type: 'array',
            message: '请至少选择一个经销商类型',
            trigger: 'change'
          }
        ],
        dealerRoleList: [
          {
            required: true,
            type: 'array',
            message: '请至少选择一个经销商权限',
            trigger: 'change'
          }
        ],
        areaData: [
          {
            required: true,
            type: 'array',
            message: '请至少选择一个代理区域',
            trigger: 'change'
          }
        ],
        dealerUserName: [],
        dealerUserPhone: [
          {
            pattern: /(\d{3,4}-?)?\d{7,8}|1\d{10}/,
            message: '格式错误',
            trigger: 'blur'
          }
        ],
        dealerUserFname: [],
        dealerUserFphone: [
          {
            pattern: /(\d{3,4}-?)?\d{7,8}|1\d{10}/,
            message: '格式错误',
            trigger: 'blur'
          }
        ],
        dealerUserNumber: [
          {
            pattern: /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
            message: '格式有误',
            trigger: 'blur'
          }
        ],
        dealerLicenseContent: [],
        dealerLicenseStart: [],
        dealerLicenseEnd: [],
        dealerScale: [],
        dealerTurnover: [],
        dealerProduct: [],
        dealerLevel: [],
        dealerStart: [],
        dealerAccountAddress: [],
        dealerAccountNumber: [
          {
            pattern: /[1-9]\d{12,18}/,
            message: '格式有误',
            trigger: 'blur'
          }
        ],
        dealerAccountName: [],
        dealerAccountPhone: [
          {
            pattern: /1\d{10}/,
            message: '格式有误',
            trigger: 'blur'
          }
        ]
      },
      dealerStatusOptions: [],
      dealerTypeOptions: [],
      dealerRoleListOptions: [],
      dealerLevelOptions: [],

      urlAction: uploadUrl,
      urlHeaders: {
        Authorization: 'Bearer ' + getToken()
      },
      dealerUserZimgUrlFileList: [],
      dealerUserFimgUrlFileList: [],
      dealerLicenseUrlFileList: [],
      //
      pending: false,
      sfzzm:false,
      sfzfm:false,
      yyzz:false
    }
  },
  computed: {
    ID() {
      return this.$route.query.id
    }
  },
  async created() {
    this.initDictsOptions('dealer_status', 'dealerStatusOptions')
    this.initDictsOptions('dealer_type', 'dealerTypeOptions')
    this.initDictsOptions('dealer_work_role', 'dealerRoleListOptions')
    this.initDictsOptions('dealer_level', 'dealerLevelOptions')
  },
  async mounted() {
    if (this.ID) {
      try {
        const res = await getDealerDetail(this.ID)
        const { dealerAddressData, areaData, ...other } = res.data
        this.formData = Object.assign(this.formData,{...other})
        // 地址相关回显
        this.formData.dealerAddress = this.$refs.cityPicker.getTextToValue(dealerAddressData)
        this.formData.dealerAddressDetail = dealerAddressData.detail
        this.formData.areaData = areaData.map((areaObj) => {
          return this.$refs.cityPicker.getTextToValue(areaObj)
        })
        // 图片回显
        imgPropArr.forEach((prop) => {
          this[prop + 'FileList'] = res.data[prop].map((per) => {
            return {
              name: per.name,
              url: per.url,
              response: {
                data: per
              }
            }
          })
         if(this[prop + 'FileList'].length!=0){
             if('dealerUserZimgUrl'===prop) {
               this.sfzzm = true;
             }else if('dealerUserFimgUrl'===prop){
               this.sfzfm=true;
           }else if('dealerLicenseUrl'===prop){
                this.yyzz=true;
             }
         }
        })
      } catch (error) {
        console.log(error)
      }
    } else {
      this.resetForm()
    }
  },
  // 编辑类不缓存
  // async activated() {
  // },
  methods: {
    async initDictsOptions(dicts, listProps) {
      try {
        const res = await this.getDicts(dicts)
        if (res.code === 200) {
          this[listProps] = res.data.map((per) => ({
            label: per.dictLabel,
            value: per.dictValue
          }))
        }
      } catch (error) {
        console.log(error)
      }
    },
    handleAreaDataAdd() {
      this.formData.areaData.push([])
    },
    handleAreaDataMinus(index) {
      this.formData.areaData.splice(index, 1)
    },
    handleRemoveZ(file, fileList) {
      this.sfzzm=false;
    },
    handleRemoveF(file, fileList) {
      this.sfzfm=false;
    },
    handleRemoveYY(file, fileList) {
      this.yyzz=false;
    },
    submitForm() {
      this.$refs['elForm'].validate(async (valid) => {
        if (!valid) return

        // if (this.$refs.url.uploadFiles.length === 0) {
        //   this.$message.error('请上传图片')
        //   return
        // }
        // 图片收集
        imgPropArr.forEach((prop) => {
          this.formData[prop] = this.$refs[prop].uploadFiles.map((per) => per.response.data)
        })

        // 地址处理
        const dealerAddressData = {
          ...this.$refs.cityPicker.getValueTextObj(this.formData.dealerAddress),
          detail: this.formData.dealerAddressDetail
        }

        // 代理区域处理
        const areaData = this.formData.areaData
          .filter((area) => {
            return area.length !== 0
          })
          .map((area) => {
            return this.$refs.cityPicker.getValueTextObj(area)
          })
        if (areaData.length === 0) {
          this.$message.error('请至少选择一个代理区域')
          return
        }

        const fetchData = {
          ...this.formData,
          dealerAddressData,
          areaData
        }

        delete fetchData.dealerAddress
        delete fetchData.dealerAddressDetail

        // console.log(fetchData)

        this.pending = true
        try {
          const fetchFn = this.ID ? updateDealer : addDealer
          const res = await fetchFn({
            ...fetchData
          })
          if (res.code === 200) {
            this.msgSuccess(res.msg)
            this.$closeNowTagsView()
          }
        } catch (error) {
          console.log(error)
        }
        this.pending = false
      })
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
      imgPropArr.forEach((prop) => {
        this.$refs[prop].clearFiles()
      })
    },
    urlBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      let isAccept = new RegExp('image/*').test(file.type)
      if (!isAccept) {
        this.$message.error('应该选择image/*类型的文件')
      }
      return isRightSize && isAccept
    },
    handleFileSuccess(response, file, fileList) {
      if (response.code !== 200) {
        const index = fileList.findIndex((per) => per.uid === file.uid)
        fileList.splice(index, 1)
        this.$message({ message: response.msg, type: 'error' })
      }
    }
  }
}
</script>

<style lang='scss'>
</style>

